package cn.sciento.farm.devicemanager.gateway.lorawan.grpc.impl;

import cn.sciento.farm.devicemanager.gateway.lorawan.config.JwtManager;
import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.GatewayService;
import cn.sciento.farm.devicemanager.gateway.lorawan.grpc.GrpcConstant;
import cn.sciento.farm.devicemanager.lorawan.*;
import io.grpc.Channel;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;

/**
 * @author wumu
 * @version V1.0
 * @date 9/15/18
 * @time 7:21 PM
 */
@Service
public class GatewayServiceImpl implements GatewayService {

    @GrpcClient(GrpcConstant.GRPC_NAME)
    private Channel serverChannel;

    @Autowired
    private JwtManager jwtManager;

    volatile GatewayServiceGrpc.GatewayServiceBlockingStub stub;


    GatewayServiceGrpc.GatewayServiceBlockingStub getStub() {
        if (stub == null) {
            synchronized (this) {
                if (stub == null) {
                    stub = GatewayServiceGrpc.newBlockingStub(serverChannel);
                }
            }
        }
        stub = stub.withCallCredentials(jwtManager.getToken());
        return stub;
    }

    @Override
    public void create(CreateGatewayRequest request) {
        getStub().create(request);
    }

    @Override
    public GetGatewayResponse Get(GetGatewayRequest request) {
        return getStub().get(request);
    }

    @Override
    public void update(UpdateGatewayRequest request) {
        getStub().update(request);
    }

    @Override
    public int delete(DeleteGatewayRequest request) {
        try {
            getStub().delete(request);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public ListGatewayResponse list(ListGatewayRequest request) {
        return getStub().list(request);
    }

    @Override
    public GetGatewayStatsResponse getStats(GetGatewayStatsRequest request) {
        return getStub().getStats(request);
    }

    @Override
    public GetLastPingResponse getLastPing(GetLastPingRequest request) {
        return getStub().getLastPing(request);
    }

    @Override
    public Iterator<StreamGatewayFrameLogsResponse> streamFrameLogs(StreamGatewayFrameLogsRequest request) {
        return getStub().streamFrameLogs(request);
    }


}
